﻿using System;
using System.Collections.Generic;
using System.IO;
using visinia.SmartEngine;
using visinia.SmartEngine.Site;

namespace visinia.web.admin.pages
{
    public partial class EditTheme : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string path = Server.MapPath(WebRoots.GetThemesRoot);
                string[] themeDirs = Directory.GetDirectories(path);
                List<string> dirs = new List<string>();
                foreach (string dir in themeDirs)
                    dirs.Add(System.IO.Path.GetFileName(dir));
                THEMES.DataSource = dirs;
                THEMES.DataBind();
                THEMES.SelectedValue = SiteSettings.Theme;
                SelectTheme();
                SelectThemeFiles();
            }
        }
        protected void THEMES_SelectedIndexChanged(object sender, EventArgs e)
        {
            SelectTheme();
            SelectThemeFiles();
        }

        private void SelectTheme()
        {
            string path = Server.MapPath(WebRoots.GetThemesRoot) + THEMES.SelectedValue;
            string[] files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
            List<string> filesList = new List<string>();
            foreach (string file in files)
            {
                if ((file.EndsWith("css")) | (file.EndsWith("master") | (file.EndsWith("ascx"))))
                    filesList.Add(file.Substring(path.Length + 1));
            }
            THEME_FILES.DataSource = filesList;
            THEME_FILES.DataBind();
        }

        protected void THEME_FILES_SelectedIndexChanged(object sender, EventArgs e)
        {
            SelectThemeFiles();
        }

        private void SelectThemeFiles()
        {
            string path = Server.MapPath(WebRoots.GetThemesRoot);
            FileContents.Text = File.ReadAllText(path + THEMES.SelectedValue + "\\" + THEME_FILES.SelectedValue);
        }

        protected void SAVE_Click(object sender, EventArgs e)
        {
            string path = Server.MapPath(WebRoots.GetThemesRoot);
            File.WriteAllText(path + THEMES.SelectedValue + "\\" + THEME_FILES.SelectedValue, FileContents.Text);
        }

        protected void CANCEL_Click(object sender, EventArgs e)
        {
            Response.Redirect(Request.RawUrl);
        }
    }
}